/**
 * Created by Administrator on 2017/1/15.
 */

var config = require('./config');

var MJ = require('../MJ/MJ');
var MJRoom = require('../MJ/room').MJRoom;

var Const = require('./const');
var SubCode = require('../subCode');


exports.LFMJRoom = MJRoom.extend({
    init: function (rid, creator, msg) {
        this._super(rid, creator, msg);
        this._dealerIndex = 1;
        this.setSaveReplay(true);

    },

    /******************************************************************
     * 重载的接口
     ******************************************************************/

    getRoomConfig: function () {
        var cfg = this._super();
        cfg.MJsettlementWait = 0;
        cfg.destroyWaitTime = 120;
        return cfg;
    },

    getInfo: function () {
        var info = this._super();
        return info;
    },

    getRoundInfo: function () {
        var info = this._super();
        return info;
    },

    getReconnectInfo: function (rePlayer) {
        var info = this._super(rePlayer);
        return info;
    },

    onBeforeStartNewRound: function () {
        this._super();

    },

    onAfterStartNewRound: function () {
        this._super();
        this.startPlay();
    },
    onBeforePlayCard: function(player, msg, card){
        var resp = this._super();
        if(resp){
            return resp;
        }else{
            if(msg.ting){
                if (!this.isPlaying()) {
                    return Code.ROOM_NOT_PLAYING;
                }
                player._huInfo.jiangs =  {};
                var tings = player.checkTing();
                if (tings.length == 0) {
                    return SubCode.TASK_UNMATCHED;
                }

                var cardNum = ExObject.sumValue(player.getHandCards());
                if (!cardNum || (cardNum%3 != 1)) {
                    return SubCode.MJ_NOT_TING;
                }
                player.setTingCards(tings);

                var tingCondition = player.getTingFan() >= 3;
                if(tingCondition == false){
                    return SubCode.MJ_CANT_TING;
                }
            }
        }
        return resp;
    },
    startPlay: function () {
        this.initPlayersHandCards();
        this._changeCurPlay(this.getDealerIndex());
        this._doCheckNewCardHangupTask();
    },



    checkNewCardHangupTask: function () {
        var player = this.getCurPlayer();
        var subConfig = this.getSubConfig();
        var room = this;
        if(player.isFirstHand()){
            var huCondition = true;
            if(room.getOption('YMP') == true){
                if(player.getColorNum() == 1){
                    huCondition = true;
                }else {
                    huCondition = false;
                }
            }
            if(player.isBaoTing() == false && huCondition){
                var huPattern = player.checkHu();
                if (huPattern != Const.Pattern.NONE) {
                    if(player.getCurFan() >= 3){
                        var rules = [];
                        /*
                         if (player.isFirstHand()) {
                         if (player.getIndex() == this.getDealerIndex()){
                         rules.push(Const.ScoreRule.TH);
                         } else {
                         rules.push(Const.ScoreRule.DIHU);
                         }
                         }
                         if (this.getCurGang()) {
                         rules.push(Const.ScoreRule.GSH);
                         }
                         */
                        var card = player.getLastCard() || player.getInitLastCard();
                        this._hangupTask.addHuTask(player.getIndex(), card, player.getIndex(), huPattern, rules);
                    }
                }
            }
        }else{
            var huCondition = true;
            if(room.getOption('YMP') == true){
                if(player.getColorNum() == 1){
                    huCondition = true;
                }else {
                    huCondition = false;
                }
            }
            if(player.isBaoTing() == false && huCondition){
                var huPattern = player.checkHu();
                if (huPattern != Const.Pattern.NONE) {
                    if(player.getCurFan() >= 3){
                        var rules = [];
                        var card = player.getLastCard() || player.getInitLastCard();
                        this._hangupTask.addHuTask(player.getIndex(), card, player.getIndex(), huPattern, rules);
                    }
                }
            }
        }
        var gangArray = player.checkGang();
        if (gangArray.length > 0) {
            this._hangupTask.addGangTask(player.getIndex(), gangArray);
        }
    },



    checkPlayCardHangupTask: function (card) {
        var player = this.getCurPlayer();
        this._checkPlayCardHangupTask(card);

    },

    _checkPlayCardHangupTask: function (card) {
        var curPlay = this.getCurPlay();
        var nextIndex = this.getNextIndex(curPlay);

        this.enumPlayers(function (eIndex, ePlayer) {
            if (eIndex != curPlay && !ePlayer.isRoundHu() ) {

                if (ePlayer.checkPengWithCard(card) ) {
                    if(ePlayer.isBaoTing() == false){
                        this._hangupTask.addPengTask(eIndex, card, curPlay);
                    }
                }
                if (ePlayer.checkGangWithCard(card)) {
                    var gang = {
                        card: card,
                        from: curPlay,
                        gang: MJ.Gang.DIAN
                    };
                    this._hangupTask.addGangTask(eIndex, [gang]);
                }
            }
        }.bind(this));
    },

    checkCurPlayHangupTask: function() {
        var player = this.getCurPlayer();

        var gangArray = player.checkGang();
        if (gangArray.length > 0) {
            this._hangupTask.addGangTask(player.getIndex(), gangArray);
        }
        this.onAfterNewCard();
    },
    checkGangHangupTask: function (playerIndex, gangInfo) {
        var card = gangInfo.card;
        if (gangInfo.type) {
            card = gangInfo.buCard;
        }
        var huIndexs = [];
        this.enumPlayers(function (eIndex, ePlayer) {
            if (eIndex != playerIndex && !ePlayer.isRoundHu() && !ePlayer.isPassHu() && ePlayer.getBaoTingPassHuTimes() < 1) {
                var huPattern = ePlayer.checkHuWithCard(card);
                if (huPattern != Const.Pattern.NONE) { // 抢杠
                    var rules = [];
                    var player = ePlayer;
                    var room = this;
                    rules.push(Const.ScoreRule.QG);
                    this._hangupTask.addHuTask(eIndex, card, playerIndex, huPattern, rules);
                    huIndexs.push(eIndex);
                }
            }
        }.bind(this));
    },

    checkHuSettlement: function () {
        return true;
    },

    onSettlementHuTask: function (task) {
        var playerIndex = task.playerIndex;
        var pattern = task.pattern;
        var card = task.card;
        var from = task.from;
        var rules = task.rules;
        var huPlayer = this.getPlayerByIndex(playerIndex);

        var isZM = (playerIndex == from); // 是否是自摸

        var targetsIndex = [];
        var targets = [];
        if (isZM) {
            this.enumPlayers(function (eIndex, ePlayer) {
                if (eIndex != playerIndex && !ePlayer.isRoundHu()) {
                    targetsIndex.push(eIndex);
                    targets.push(ePlayer);
                }
            });
        } else {
            huPlayer.addRoundItemScores(Const.ScoreRule.DH, Const.ItemScore[Const.ScoreRule.DH]);
            huPlayer.setRoundScoreRule(Const.ScoreRule.DH);
            targetsIndex.push(from);
            targets.push(this.getPlayerByIndex(from));
        }
        logger.debug("beforeHuRules: %j", rules);
        for (var i = 0; i < rules.length; ++i) {
            var rule = rules[i];
            switch (rule) {
                case Const.ScoreRule.QG:
                    if (!isZM) {
                        var targetPlayer = targets[0];
                        if (targetPlayer.getIndex() == this.getCurPlay() && this.getCurGang() > 0) { // 抢杠的被抢玩家一定是当前玩家
                            targetPlayer.setRoundScoreRule(rule);
                            targetPlayer.cancelLastGangForQG(card);
                        }
                    }
                    break;
                case Const.ScoreRule.GSP:
                    if (!isZM) {
                        var targetPlayer = targets[0];
                        targetPlayer.setLastGangUnscored();
                    }
                    break;
                default:
                    break;
            }
            huPlayer.setRoundScoreRule(rule);
            huPlayer.addRoundItemScores(rule, Const.ItemScore[rule]);
        }

        var patternScore = Const.PatternScore[pattern];
        var huResult = isZM ? MJ.Result.ZM : MJ.Result.DH;

        huPlayer.setRoundResult(huResult, targetsIndex, card);
        huPlayer.setRoundPattern(pattern, patternScore);
        huPlayer.settlementRules();
        this.broadcastReplay("onPlayerHu", {
            playerIndex: playerIndex,
            card: card,
            from: from,
        });
    },

    onSettlement: function () {
        var room = this;
        var ye = 0;

        var huPlayer = room.getPlayerByIndex(room.getFirstHuPlayerIndex());
        if(room.getOption('SY') == true){
            ye = huPlayer.getMaxColorCardsNum();
        }
        var gang = huPlayer.getGangFan();
        var score = huPlayer.getRoundItemScore();
        if(huPlayer.getIndex() == room.getDealerIndex()){
            var curScore = score + gang + ye;
            this.enumPlaying(function(eIndex, ePlayer){
                if(eIndex == huPlayer.getIndex){
                    return;
                }
                ePlayer.addRoundScore(-curScore);
                huPlayer.addRoundScore(curScore);
            });
        }else {
            var curScore = score + gang;
            this.enumPlaying(function(eIndex, ePlayer){
                if(eIndex == huPlayer.getIndex){
                    return;
                }
                if(ePlayer.getIndex() == room.getDealerIndex()){
                    curScore += ye;
                }
                ePlayer.addRoundScore(-curScore);
                huPlayer.addRoundScore(curScore);
            });
        }
    },

    onCurRoundFinished: function () {
        this._super();
        // 计算新的庄家
        if(this.getFirstHuPlayerIndex() == this.getDealerIndex()){
            this._dealerLZ += 1;
        }else {
            this._dealerIndex = this.getNextIndex(this._dealerIndex);
            this._dealerLZ = 1;
        }
        this.broadcastReplay("onDealerChanged", {
            dealer: this._dealerIndex,
            dealerLZ: this._dealerLZ
        });
    },


    /******************************************************************
     * 消息处理
     ******************************************************************/


    /******************************************************************
     * 功能接口
     ******************************************************************/

    /**
     * 结算玩家是否听牌
     * @param player
     * @private
     */


});